package com.applink.sell_proof.fragment;

import java.util.ArrayList;
import java.util.Calendar;
import java.util.GregorianCalendar;
import java.util.List;
import java.util.Observable;
import java.util.Observer;

import android.app.DatePickerDialog;
import android.app.DatePickerDialog.OnDateSetListener;
import android.content.Context;
import android.database.Cursor;
import android.os.Bundle;
import android.os.Handler;
import android.os.SystemClock;
import android.support.v4.app.FragmentTransaction;
import android.support.v4.content.CursorLoader;
import android.support.v4.content.Loader;
import android.text.InputType;
import android.text.format.DateFormat;
import android.view.KeyEvent;
import android.view.LayoutInflater;
import android.view.MotionEvent;
import android.view.View;
import android.view.View.OnClickListener;
import android.view.ViewGroup;
import android.view.inputmethod.EditorInfo;
import android.view.inputmethod.InputMethodManager;
import android.widget.AbsListView;
import android.widget.AbsListView.OnScrollListener;
import android.widget.AdapterView;
import android.widget.AdapterView.OnItemSelectedListener;
import android.widget.ArrayAdapter;
import android.widget.DatePicker;
import android.widget.EditText;
import android.widget.ListView;
import android.widget.Spinner;
import android.widget.TextView;
import android.widget.TextView.OnEditorActionListener;

import com.actionbarsherlock.app.SherlockFragment;
import com.actionbarsherlock.view.Menu;
import com.actionbarsherlock.view.MenuInflater;
import com.actionbarsherlock.view.MenuItem;
import com.applink.sell_proof.AllProjectActivity;
import com.applink.sell_proof.R;
import com.applink.sell_proof.api.DataHelper;
import com.applink.sell_proof.api.DataResult;
import com.applink.sell_proof.api.Methods;
import com.applink.sell_proof.builder.AllProjectBuilder;
import com.applink.sell_proof.constant.Constant;
import com.applink.sell_proof.constant.ItemStatus;
import com.applink.sell_proof.database.EMarketingContentProvider;
import com.applink.sell_proof.database.table.DealDBHelper;
import com.applink.sell_proof.model.Project;
import com.applink.sell_proof.util.SimpleEntry;

public class AllProjectFragment extends SherlockFragment implements Observer,
		OnScrollListener, OnEditorActionListener, OnItemSelectedListener,
		OnClickListener, OnDateSetListener {

	protected ViewGroup mLayout;
	protected AllProjectBuilder mOpportunityBuider;
	protected String mCategorySearch;
	private EditText mSearchBox;

	@Override
	public View onCreateView(LayoutInflater inflater, ViewGroup container,
			Bundle savedInstanceState) {
		if (mLayout == null) {
			mLayout = (ViewGroup) inflater.inflate(R.layout.alldeal, null,
					false);
			mOpportunityBuider = new AllProjectBuilder(getActivity(), mLayout);
		} else {
			if (mLayout.getParent() != null) {
				((ViewGroup) mLayout.getParent()).removeView(mLayout);
			}
		}

		setHasOptionsMenu(true);
		((ListView) mLayout.findViewById(android.R.id.list))
				.setOnScrollListener(this);

		initDataAtFirstTime();

		return mLayout;
	}

	public void onPause() {
		super.onPause();
		DataHelper.getInstance().deleteObserver(this);
	}

	/**
	 * because this is the default fragment so it need to load the data by
	 * itself, not by changing selector event. Override this method to prevent
	 * unnecessary data load
	 */
	protected void initDataAtFirstTime() {
		DataHelper.getInstance().addObserver(this);
		getOpportunity();
	}

	@Override
	public void onCreateOptionsMenu(Menu menu, MenuInflater inflater) {
		inflater.inflate(R.menu.menu_deal, menu);
		MenuItem search_bar = menu.findItem(R.id.search_bar);
		Spinner spinner = (Spinner) search_bar.getActionView().findViewById(
				R.id.search_spinner);

		mSearchBox = (EditText) search_bar.getActionView().findViewById(
				R.id.et_search_bar);
		mSearchBox.setOnEditorActionListener(this);

		List<SimpleEntry<String, String>> types = new ArrayList<SimpleEntry<String, String>>();
		types.add(new SimpleEntry<String, String>(
				Constant.KEY_SEARCH_DEAL_BY_NAME, "By Name"));
		types.add(new SimpleEntry<String, String>(
				Constant.KEY_SEARCH_DEAL_BY_CLOSEDATE, "Closing Date"));
		ArrayAdapter<SimpleEntry<String, String>> adapter = new ArrayAdapter<SimpleEntry<String, String>>(
				getActivity(), R.layout.spinner_search, types);
		spinner.setAdapter(adapter);
		spinner.setOnItemSelectedListener(this);
	}

	@Override
	public boolean onOptionsItemSelected(MenuItem item) {

		switch (item.getItemId()) {

		case R.id.search_bar: {
			// show keyboard
			final EditText searchBox = (EditText) item.getActionView()
					.findViewById(R.id.et_search_bar);
			searchBox.clearFocus();
			(new Handler()).postDelayed(new Runnable() {
				public void run() {
					searchBox.dispatchTouchEvent(MotionEvent.obtain(
							SystemClock.uptimeMillis(),
							SystemClock.uptimeMillis(),
							MotionEvent.ACTION_DOWN, 0, 0, 0));
					searchBox.dispatchTouchEvent(MotionEvent.obtain(
							SystemClock.uptimeMillis(),
							SystemClock.uptimeMillis(), MotionEvent.ACTION_UP,
							0, 0, 0));
				}
			}, 100);
			return true;
		}
		default:
			return false;
		}

	}

	protected int getLoaderId() {
		return AllProjectActivity.LOADER_DRAFT_ID;
	}

	protected Loader<Cursor> initLoader() {
		return new CursorLoader(getActivity(),
				EMarketingContentProvider.DEAL_CONTENT_URI, null, null, null,
				DealDBHelper.INVOICEDATE + " DESC");
	}

	protected int mVisibleItem;
	protected int mFirstVisibleItem;

	@Override
	public void onScroll(AbsListView view, int firstVisibleItem,
			int visibleItemCount, int totalItemCount) {
		mVisibleItem = visibleItemCount;
		mFirstVisibleItem = firstVisibleItem;
	}

	@Override
	public void onScrollStateChanged(AbsListView view, int scrollState) {
		if (scrollState == SCROLL_STATE_IDLE
				&& mVisibleItem > 0
				&& mFirstVisibleItem + mVisibleItem >= mOpportunityBuider
						.getData().size()) {
		}
	}

	@Override
	public boolean onEditorAction(TextView v, int actionId, KeyEvent event) {

		if (actionId == EditorInfo.IME_ACTION_SEARCH) {

			SearchProject searchResult = (SearchProject) getActivity()
					.getSupportFragmentManager().findFragmentByTag(
							SearchProject.TAG);

			if (searchResult == null)
				searchResult = new SearchProject();

			FragmentTransaction transaction = getActivity()
					.getSupportFragmentManager().beginTransaction();

			transaction.add(R.id.main_container, searchResult,
					SearchProject.TAG);
			transaction.addToBackStack(null);
			transaction.commit();

			searchResult.searchDeal(mCategorySearch, v.getText().toString(),
					getActivity());

			InputMethodManager imm = (InputMethodManager) getActivity()
					.getSystemService(Context.INPUT_METHOD_SERVICE);
			imm.hideSoftInputFromWindow(v.getWindowToken(), 0);
			return true;
		}
		return false;
	}

	@Override
	public void onItemSelected(AdapterView<?> adapterView, View arg1, int arg2,
			long arg3) {
		@SuppressWarnings("unchecked")
		SimpleEntry<String, String> map = (SimpleEntry<String, String>) adapterView
				.getSelectedItem();
		mCategorySearch = map.getKey();
		mSearchBox.getEditableText().clear();
		if (map.getKey().equals(Constant.KEY_SEARCH_DEAL_BY_CLOSEDATE)) {
			mSearchBox.setHint("enter closing date");
			mSearchBox.setInputType(InputType.TYPE_CLASS_DATETIME);
			mSearchBox.setOnClickListener(this);
			mSearchBox.setFocusable(false);
		} else {
			mSearchBox.setFocusable(true);
			mSearchBox.setEnabled(true);
			mSearchBox.setHint("enter deal name");
			mSearchBox.setOnClickListener(null);
		}
	}

	@Override
	public void onNothingSelected(AdapterView<?> arg0) {
	}

	@Override
	public void onClick(View v) {
		System.currentTimeMillis();
		DatePickerDialog dateDialog = new DatePickerDialog(getActivity(), this,
				Calendar.getInstance().get(Calendar.YEAR), Calendar
						.getInstance().get(Calendar.MONTH), Calendar
						.getInstance().get(Calendar.DAY_OF_MONTH));
		dateDialog.setTitle(R.string.close_date);
		dateDialog.show();

	}

	@Override
	public void onDateSet(DatePicker view, int year, int monthOfYear,
			int dayOfMonth) {
		GregorianCalendar closeDate = new GregorianCalendar(year, monthOfYear,
				dayOfMonth);
		String textDate = DateFormat.getDateFormat(getActivity()).format(
				closeDate.getTimeInMillis());
		mSearchBox.setText(textDate);
		SearchProject searchResult = (SearchProject) getActivity()
				.getSupportFragmentManager().findFragmentByTag(
						SearchProject.TAG);
		if (searchResult == null)
			searchResult = new SearchProject();
		FragmentTransaction transaction = getActivity()
				.getSupportFragmentManager().beginTransaction();
		transaction.add(R.id.main_container, searchResult, SearchProject.TAG);
		transaction.addToBackStack(null);
		transaction.commit();
		searchResult.searchDeal(mCategorySearch,
				String.format("%d-%d-%d", year, monthOfYear + 1, dayOfMonth),
				getActivity());
	}

	@Override
	public void update(Observable observable, Object data) {

		if (data != null) {
			DataResult result = (DataResult) data;
			if (result.getMethodName() == Methods.getOpportunityByStatus) {

				String tagname = (String) result.getMethodParam()
						.getInputData();

				if (tagname.equals(getTagName())) {
					@SuppressWarnings("unchecked")
					List<Project> projects = (List<Project>) result.getData();
					mOpportunityBuider.setData(projects);
				}
				observable.deleteObserver(this);
			}
		}
	}

	/**
	 * 
	 * @return
	 */
	protected String getTagName() {
		return this.getClass().getName();
	}

	/**
	 * 
	 */
	public void getOpportunity() {
		// DataHelper.getInstance().getOpportunityByStatus(
		// "'Pending approval', 'Approved', 'Not Approved', 'Draft'",
		// getTagName());

		DataHelper.getInstance().getOpportunityByStatus(
				"'" + ItemStatus.PENDING + "', '" + ItemStatus.APPROVED + "', '"
						+ ItemStatus.NOT_APPROVED + "', '" + ItemStatus.DRAFT + "'",
				getTagName());
	}
}
